#include "yzjthread.h"

YZJThread::YZJThread()
{
    pthread_mutex_init(&mutex, NULL);

//    fp = oFile.OpenFile("record.yzj", "a+");
    file.setFileName("record.yzj");
    if(!file.open(QIODevice::WriteOnly | QIODevice::ReadOnly)){
//        QMessageBox::warning(this
//                             ,QObject::tr("File Operation:"))
//                             ,QObject::tr("Cannot operate file %1.\n%2")
//                             .arg(file.fileName())
//                             .arg(file.errorString());
        QMessageBox msg;
        msg.setText("CAN OPEN record.yzj");
        msg.exec();
    }
}

YZJThread::~YZJThread(){
    void *rev = NULL;

    pthread_join(readThread,&rev);
    pthread_join(writeThread,&rev);
    pthread_mutex_destroy(&mutex);

    file.close();
//    oFile.CloseFile(fp);
}

void YZJThread::RunWrite(){
    err = pthread_create(&readThread, NULL, writeFunction, NULL);
    if(err != 0){
        printf("write thread create error.\n");
        exit(1);
    }
}

void YZJThread::RunRead(QTreeWidget *tw){
    err = pthread_create(&writeThread, NULL, readFunction,(void*)tw);
    if(err != 0){
        printf("thread create error.\n");
        exit(1);
    }
}

void *YZJThread::readFunction(void *arg){
    static int count = 0;
    while(1){
        sleep(2);

        pthread_mutex_lock(&mutex);

        YzjReader oReader((QTreeWidget*)arg);
        // 找到文件开始位置
        file.seek(0);
        oReader.ReadYzj(&file);

        if(count >= 10){
            pthread_t computeThread;
            int err = pthread_create(&computeThread, NULL, computeFunction, NULL);
            if(err != 0){
                perror("Computer thread create fail.\n");
                exit(1);
            }
            // 重新开始计数
            count = 0;
        }
        count ++;
        pthread_mutex_unlock(&mutex);
    }
}

void *YZJThread::writeFunction(void *arg){
    while(1){
        sleep(2);

        pthread_mutex_lock(&mutex);

        // 此接口需要QFile
        // 清空现存文件内容，使得yzj文件中始终只有一个记录
        YzjWriter oWriter;
        oWriter.WriteYzj(&file); // 将QMultiMap中内容写入到yzj文件
        file.flush();   // 真正写入文件
        pthread_mutex_unlock(&mutex);
    }
}

void *YZJThread::computeFunction(void *arg){
    AbnormalCompute oComputor;
    oComputor.Compute();
    return ((void*)0);
}
